#include "mymapwidget.h"
#include "ui_mymapwidget.h"
#include <QDebug>
#include <QJsonObject>
#include <QJsonDocument>
#include <QNetworkReply>
#include <QJsonArray>
MyMapWidget::MyMapWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MyMapWidget)
{
    ui->setupUi(this);
    setWindowTitle("车载地图");
    ui->mapWidget->setStyleSheet("QWidget{border-image:url(:/image/map/default.jpeg);}");
    this->setWindowFlags(Qt::FramelessWindowHint);

    installEventFilter(this);
    connect(&m_locDefaultManager,SIGNAL(finished(QNetworkReply*)),this,SLOT(onGetDefaultLocation(QNetworkReply*)));
    connect(&m_searchDefaultManager,SIGNAL(finished(QNetworkReply*)),this,SLOT(onGetSearchLocation(QNetworkReply*)));

    getDefaultLocation();
}

MyMapWidget::~MyMapWidget()
{
    delete ui;
}
bool flag = false;
bool MyMapWidget::eventFilter(QObject *watched, QEvent *event)
{

    bool pressflag=true,releaseflag=true;
    QPoint point,lpoint;
    double mx,my;
    double movex,movey;
    if(watched==this)
    {

        switch (event->type()) {
        case QEvent::MouseButtonPress:
            pressflag = true;
            lpoint.setY(cursor().pos().y());
            lpoint.setX(cursor().pos().x());

            break;
        case QEvent::MouseButtonRelease:
            releaseflag = true;
            flag = true;
            point.setY(cursor().pos().y());
            point.setX(cursor().pos().x());
            break;
        default:
            break;
        }
    }
    if(releaseflag&&pressflag)
    {

        releaseflag = false;
        pressflag = false;
        mx = point.x() - lpoint.x();
        my = point.y() - lpoint.y();

        if(mx>5||mx<-5||my>5||my<-5){
            QString stmpscale = m_scale;
            movex = mx*0.000004*(19-stmpscale.toInt())*(19-stmpscale.toInt());
            movey = my*0.000004*(19-stmpscale.toInt())*(19-stmpscale.toInt());

            m_lng -= movex;
            m_lat += movey;

            m_marker = QString("%1,%2").arg(m_lng).arg(m_lat);

            if(flag)
            {

              sendMapRequest();
              flag = false;
            }
        }
    }
    return QWidget::eventFilter(watched,event);
}
void MyMapWidget::getDefaultLocation(){
    m_locDefaultManager.get(QNetworkRequest(QUrl(QString("http://api.map.baidu.com/location/ip?ak=%1&coor=bd09ll").arg("0IdURarqEPGuWqUp6TM7ftDQKMpeVdwu"))));
}

void MyMapWidget::onGetSearchLocation(QNetworkReply* reply){

    QJsonObject data = QJsonDocument::fromJson(reply->readAll()).object();

    QJsonArray results = data.value("results").toArray();

    QJsonObject ob = results.at(0).toObject();

    QJsonObject xy = ob.value("location").toObject();

    m_lng = xy.value("lng").toDouble();
    m_lat = xy.value("lat").toDouble();


    if(m_lat&&m_lng)
    {
      m_city ="";
      m_marker = QString("%1,%2").arg(m_lng).arg(m_lat);
      m_scale = "17";
      sendMapRequest();
    }
    else {
        qDebug()<<"no search location";
    }

}
void MyMapWidget::onGetDefaultLocation(QNetworkReply* reply){

  QJsonObject data = QJsonDocument::fromJson(reply->readAll()).object();

  QJsonObject xy = data.value("content").toObject().value("point").toObject();

  m_lat = xy.value("y").toString().toDouble();
  m_lng = xy.value("x").toString().toDouble();

  if(m_lat&&m_lng)
  {
    m_city ="";
    m_marker = QString("%1,%2").arg(m_lng).arg(m_lat);
    m_scale = "12";
    m_defaultloc = QString("%1,%2").arg(m_lat).arg(m_lng);
    sendMapRequest();
  }
  else {
      qDebug()<<"no location";
  }

}
void MyMapWidget::sendMapRequest(){

    QString request_msg = QString("http://api.map.baidu.com/staticimage?center=%1&markers=%2&zoom=%3&width=581&height=361").arg(m_city).arg(m_marker).arg(m_scale);
    m_request.setUrl(QUrl(request_msg.toUtf8().data()));
    m_reply = m_mapManager.get(m_request);
    connect(m_reply,&QNetworkReply::finished,this,&MyMapWidget::ready_Read);
}

void MyMapWidget::ready_Read()
{
    m_filename = "map.png";
    m_file.close();
    m_file.setFileName(m_filename);
    m_file.open(QIODevice::ReadWrite | QIODevice::Truncate);

    m_timer.start(4);
    connect(&m_timer,&QTimer::timeout,[=](){
      m_timer.stop();

        m_file.write(m_reply->readAll());

        QPixmap pixmap;
        if(pixmap.load(m_filename))
            ui->mapWidget->setStyleSheet("QWidget{border-image:url(./map.png);}");
    });
}
void MyMapWidget::on_searchBtn_clicked()
{
    QString loc = ui->searchEdit->text();
    m_searchDefaultManager.get(QNetworkRequest(QUrl(QString("http://api.map.baidu.com/place/v2/search?query=%1&location=%2&output=json&radius=20000&ak=%3").arg(loc).arg(m_defaultloc).arg("0IdURarqEPGuWqUp6TM7ftDQKMpeVdwu"))));

}
void MyMapWidget::on_reduceBtn_clicked()
{
    if(m_scale.toInt()>3)
    {
        int newscale = m_scale.toInt()-1;
        m_scale.clear();
        m_scale = QString("%1").arg(newscale);
        sendMapRequest();
    }

}

void MyMapWidget::on_enlargeBtn_clicked()
{
    if(m_scale.toInt()<19)
    {
        int newscale = m_scale.toInt()+1;
        m_scale.clear();
        m_scale = QString("%1").arg(newscale);
        sendMapRequest();
    }
}

void MyMapWidget::on_pushButton_clicked()
{
    this->close();
}
